import { Application } from 'egg';
import * as pageFindPlugin from 'mongoose-paginate';
import { PostStatus, nthunailpostfix } from '../constants';
import * as moment from 'moment';
moment.locale('zh-cn');

export default (app: Application) => {
  const mongoose = app.mongoose;
  const ObjectId = mongoose.Schema.Types.ObjectId;
  const postSchema = new mongoose.Schema({
    // 网点ID
    siteId: ObjectId,
    // 发布用户ID
    authorId: {
      type: ObjectId,
      retquied: true,
      ref: 'User',
    },
    // 帖子分类
    postType: {
      type: ObjectId,
      required: true,
      ref: 'Category',
    },
    // 帖子文案
    postText: String,
    // 帖子配图
    postImgs: [ String ],
    // 帖子发布时间
    createAt: Date,
    // 帖子发布地址
    addressName: String,
    // 帖子发布经纬度
    coordinate: [ Number ],
    // 点赞的用户
    likes: [{
      // 用户ID
      userId: ObjectId,
      // 头像
      avatar: String,
      // 昵称
      name: String,
    }],
    liked: {
      type: Boolean,
      default: false,
      required: true,
    },
    // 点赞数量
    likesCount: Number,
    // 评论id
    comments: [{
      type: ObjectId,
      required: false,
      ref: 'Comments',
    }],
    // 评论数量
    commentsCount: Number,
    // 帖子状态(0: 已发布(默认), 1: 已删除)
    status: {
      type: Number,
      default: PostStatus.published,
      enum: [ PostStatus.published, PostStatus.deleted ],
    },
    // 是否置顶
    isTop: Boolean,
    // 是否精华
    isGood: Boolean,
    // 是否被锁定
    isLock: Boolean,
  }, {
      toJSON: { virtuals: true, getters: true, }, timestamps: { createdAt: true },
    });
  // 时间戳
  // tslint:disable-next-line:ter-prefer-arrow-callback
  postSchema.virtual('timestamp').get(function (this: any) {
    const diff: number = moment(new Date()).diff(this.createdAt) / 1000;
    const second: number = 60;
    const hour: number = second * 60;
    const day: number = hour * 24;
    let result: string = `${Math.round(diff / day)}天之前`;
    if (diff < second) {
      result = `${Math.round(diff)}秒之前`;
    } else if (diff >= second && diff < hour) {
      result = `${Math.round(diff / second)}分之前`;
    } else if (diff >= hour && diff < day) {
      result = `${Math.round(diff / hour)}小时之前`;
    }
    return result;
    });
  // 缩略图
  // tslint:disable-next-line:ter-prefer-arrow-callback
  postSchema.virtual('thumbnail').get(function(this: any) {
    const postImgs = this.postImgs;
    const thumbnail: string[] = [];
    let postfix = nthunailpostfix[2];
    if (postImgs.length === 1) {
      postfix = nthunailpostfix[0];
    }
    if (postImgs.length === 2) {
      postfix = nthunailpostfix[1];
    }
    postImgs.forEach((element: string) => {
      thumbnail.push(`${element}?${postfix}`);
    });
    return thumbnail;
  });
  postSchema.index({ postType: 1, status: 1 });
  postSchema.index({ postText: 1, authorId: 1 }, { unique: true });
  postSchema.plugin(pageFindPlugin, {});
  return mongoose.model('Post', postSchema);
};
